// Main JavaScript for benchmark visualization

let reports = [];
let currentScores = null;
let baselineId = null;
let selectedModels = [];
let dataTable = null;

/**
 * Load all reports from the server
 */
function loadReports() {
    $.ajax({
        url: '/api/reports',
        method: 'GET',
        success: function(data) {
            reports = data.reports;
            populateDeviceList();
            populateBaselineSelect();
            extractModels();
            calculateScores();
        },
        error: function(xhr, status, error) {
            console.error('Failed to load reports:', error);
            alert('加载报告失败：' + error);
        }
    });
}

/**
 * Populate device list display
 */
function populateDeviceList() {
    const container = $('#deviceList');
    container.empty();
    
    if (reports.length === 0) {
        container.html('<span class="text-muted">未加载任何报告</span>');
        return;
    }
    
    reports.forEach(report => {
        const badge = $('<span>')
            .addClass('badge bg-secondary device-badge')
            .text(`${report.id} (${report.num_models})`);
        container.append(badge);
    });
}

/**
 * Populate baseline selection dropdown
 */
function populateBaselineSelect() {
    const select = $('#baselineSelect');
    const currentValue = select.val(); // 保存当前选中值
    select.empty();
    select.append('<option value="">自动选择</option>');
    
    reports.forEach(report => {
        select.append(`<option value="${report.id}">${report.id}</option>`);
        console.log(`${report.id}: ${report.num_models}`);
    });
    
    // 恢复之前的选中值
    if (currentValue) {
        select.val(currentValue);
    }
}

/**
 * 从后端获取所有报告中的模型名称
 * 通过API遍历所有reports[i].models进行汇总
 */
function extractModels() {
    // 调用后端API获取所有模型名称
    $.ajax({
        url: '/api/models',
        method: 'GET',
        success: function(data) {
            // 保存模型列表
            selectedModels = data.models || [];
            
            // 如果没有任何模型，使用常见模型作为降级方案
            if (selectedModels.length === 0) {
                console.warn('No models found in reports, using fallback list');
                selectedModels = ['resnet50', 'bert', 'mobilenetv2', 'vit'];
            }
            
            console.log('Available models:', selectedModels);
            
            // 渲染模型筛选checkbox
            populateModelFilters();
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch models:', error);
            // 降级使用常见模型列表
            selectedModels = ['resnet50', 'bert', 'mobilenetv2', 'vit'];
            populateModelFilters();
        }
    });
}

/**
 * 解释：
 * 
 * 该函数 `populateModelFilters` 用于在前端页面动态生成一组模型筛选的多选框（checkbox），
 * 以便用户可以选择参与评分计算的模型。具体做法如下：
 * 
 * 1. 首先获取页面上用于显示模型筛选器的容器元素（id="modelFilters"），并清空其内容。
 * 2. 如果 `selectedModels` 数组为空（即没有可用的模型），就在容器中显示“未找到模型”的提示信息，并返回。
 * 3. 遍历所有 `selectedModels`，为每一个模型执行以下步骤：
 *    a) 创建一个用于横向排列的 `<div class="form-check form-check-inline">`。
 *    b) 在 `<div>` 内插入一个多选框元素 `<input type="checkbox">`，其 id 为 model_模型名，默认勾选，且绑定上 `change` 事件，每当用户勾选发生变化时会自动调用 `calculateScores()` 重新计分。
 *    c) 创建对应的 `<label>` 元素，指向该多选框，并显示模型的名字。
 *    d) 把该多选框和标签一起添加到 div 容器，再将 div 插入到总体容器中。
 * 
 * 这样，前端就能根据 `selectedModels` 的内容，动态渲染所有模型的勾选筛选项，实现灵活的模型选择与自动计分联动。
 */
function populateModelFilters() {
    const container = $('#modelFilters');       // 获取包含模型多选框的容器
    container.empty();                          // 先清空内容

    if (selectedModels.length === 0) {          // 没有模型可选时显示提示
        container.html('<span class="text-muted">未找到模型</span>');
        return;
    }

    selectedModels.forEach(model => {           // 遍历所有模型
        const div = $('<div>').addClass('form-check form-check-inline'); // 横向排列

        // 创建复选框，id带模型名，默认勾选，切换时会重新计分
        const checkbox = $('<input>')
            .addClass('form-check-input')
            .attr('type', 'checkbox')
            .attr('id', `model_${model}`)
            .attr('checked', true)
            .on('change', calculateScores);

        // 创建label，指向该checkbox，文本为模型名
        const label = $('<label>')
            .addClass('form-check-label')
            .attr('for', `model_${model}`)
            .text(model);

        div.append(checkbox, label);   // div内并排放入checkbox和label
        container.append(div);         // 容器中插入该div，显示在页面
    });
}


/**
 * Update baseline device
 */
function updateBaseline() {
    const newBaselineId = $('#baselineSelect').val() || null;
    
    // 如果基准没有变化，不需要重新计算
    if (newBaselineId === baselineId) {
        return;
    }
    
    baselineId = newBaselineId;
    
    // 显示提示信息
    console.log(`切换基准设备为: ${baselineId}`);
    
    // 更新当前基准信息（临时显示正在切换）
    $('#currentBaselineInfo').html(
        `<i class="fas fa-spinner fa-spin"></i> 正在切换基准至: ${baselineId}...`
    );
    
    // 重新计算评分
    calculateScores();
}

/**
 * Calculate scores for all reports
 * 
 * 向后端 /api/score 接口发送请求，计算所有报告的评分。
 * - POST /api/score
 *   body: {
 *     report_ids: ["test", ...],   // 要评分的报告ID列表
 *     baseline_id: "device1",      // 选中的基准设备（可为null代表自动）
 *     models: ["resnet50", ...]    // 当前选中的模型（可为null代表全部）
 *   }
 * 后端返回新的评分数据（见 scorer.py 逻辑）。
 */
function calculateScores() {
    if (reports.length === 0) {
        return;
    }
    
    $('#loadingScores').show();
    $('#scoreTable').hide();
    
    // Get selected models
    const models = [];
    selectedModels.forEach(model => {
        if ($(`#model_${model}`).is(':checked')) {
            models.push(model);
        }
    });
    
    const requestData = {
        report_ids: reports.map(r => r.id),
        baseline_id: baselineId,
        models: models.length > 0 ? models : null
    };
    
    // 向后端 /api/score 发送评分计算请求
    $.ajax({
        url: '/api/score', // 评分计算API
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function(data) {
            currentScores = data;
            
            // 同步基准选择器：如果后端返回了基准ID，更新选择器
            if (data.baseline) {
                baselineId = data.baseline;
                $('#baselineSelect').val(data.baseline);
            }
            
            displayScores(data);
            updateCharts(data);
            updateDetailsTable(data);
            $('#loadingScores').hide();
            $('#scoreTable').show();
        },
        error: function(xhr, status, error) {
            console.error('Failed to calculate scores:', error);
            alert('计算评分失败：' + error);
            $('#loadingScores').hide();
        }
    });
}

/**
 * Display scores in the leaderboard table
 */
function displayScores(data) {
    // 更新当前基准信息显示
    const baselineInfo = `当前基准: ${data.baseline|| '未知'} (所有维度 = 100 分)`;
    $('#currentBaselineInfo').html(`<i class="fas fa-info-circle"></i> ${baselineInfo}`);
    console.log(`当前基准设备: ${data.baseline} (${data.baseline})`);
    
    // 先销毁现有的 DataTable（如果存在）
    if (dataTable) {
        dataTable.destroy();
        dataTable = null;
    }
    
    // 清空并重新填充表格
    const tbody = $('#scoresTableBody');
    tbody.empty();
    
    data.scores.forEach((score, index) => {
        const isBaseline = score.id === data.baseline;
        const rank = index + 1;
        
        let rowClass = '';
        if (score.total_score >= 150) {
            rowClass = 'score-excellent';
        } else if (score.total_score >= 120) {
            rowClass = 'score-good';
        } else if (isBaseline) {
            rowClass = 'score-baseline';
        } else if (score.total_score < 70) {
            rowClass = 'score-poor';
        }
        
        const row = $('<tr>').addClass(rowClass);
        
        // Rank badge
        let rankBadge = '';
        if (rank === 1) {
            rankBadge = '<span class="badge badge-rank-1"><i class="fas fa-trophy"></i> 1</span>';
        } else if (rank === 2) {
            rankBadge = '<span class="badge badge-rank-2"><i class="fas fa-medal"></i> 2</span>';
        } else if (rank === 3) {
            rankBadge = '<span class="badge badge-rank-3"><i class="fas fa-medal"></i> 3</span>';
        } else {
            rankBadge = `<span class="badge bg-secondary">${rank}</span>`;
        }
        
        row.append($('<td>').html(rankBadge));
        
        // 设备名称列 - 添加hover提示和详情按钮
        const deviceCell = $('<td>');
        const deviceNameSpan = $('<span>')
            .attr('data-report-id', score.id)
            .attr('data-bs-toggle', 'popover')
            .attr('data-bs-trigger', 'hover')
            .attr('data-bs-placement', 'right')
            .attr('data-bs-html', 'true')
            .css('cursor', 'pointer')
            .css('border-bottom', '1px dotted #999')
            .text(score.id + (isBaseline ? ' (基准)' : ''));
        
        const detailBtn = $('<button>')
            .addClass('btn btn-sm btn-outline-info ms-2')
            .attr('title', '查看详细信息')
            .html('<i class="fas fa-info-circle"></i>')
            .on('click', function() {
                showDeviceDetails(score.id);
            });
        
        deviceCell.append(deviceNameSpan).append(detailBtn);
        row.append(deviceCell);
        
        row.append($('<td>').html(`<strong>${score.total_score}</strong>`));
        row.append($('<td>').text(score.performance_score));
        row.append($('<td>').text(score.efficiency_score !== null ? score.efficiency_score : 'N/A'));
        row.append($('<td>').text(score.resource_score));
        row.append($('<td>').text(score.stability_score));
        
        tbody.append(row);
    });
    
    // 使用 setTimeout 确保 DOM 更新完成后再初始化 DataTable 和 Popover
    setTimeout(function() {
        dataTable = $('#scoresDataTable').DataTable({
            paging: false,
            searching: false,
            info: false,
            order: [[2, 'desc']],
            retrieve: true  // 如果表格已存在则重用
        });
        
        // 初始化所有Popover
        initializePopovers();
    }, 100);
}

/**
 * Initialize Bootstrap Popovers for device names
 * 为设备名称初始化Bootstrap Popover提示
 */
function initializePopovers() {
    // 销毁旧的popover
    $('[data-bs-toggle="popover"]').popover('dispose');
    
    // 为每个设备名称创建popover
    $('[data-bs-toggle="popover"]').each(function() {
        const reportId = $(this).data('report-id');
        const popoverContent = generatePopoverContent(reportId);
        
        $(this).popover({
            content: popoverContent,
            html: true,
            trigger: 'hover',
            placement: 'right',
            container: 'body'
        });
    });
}

/**
 * Generate popover content for a device
 * 生成设备的Popover内容（简要信息）
 */
function generatePopoverContent(reportId) {
    // 从后端获取完整报告数据
    const report = getReportData(reportId);
    
    if (!report) {
        return '<div class="text-muted">加载中...</div>';
    }
    
    const env = report.env || {};
    const system = env.system || {};
    const cpu = env.cpu || {};
    const gpu = env.gpu || {};
    const run = report.run || {};
    
    // 检测GPU信息
    let gpuInfo = '<span class="text-muted">无</span>';
    if (gpu.nvidia && gpu.nvidia.devices && gpu.nvidia.devices.length > 0) {
        const device = gpu.nvidia.devices[0];
        gpuInfo = `${device.name}<br><small class="text-muted">${device.memory_total_gb.toFixed(1)} GB | Driver: ${device.driver_version}</small>`;
    } else if (gpu.amd && gpu.amd.devices && gpu.amd.devices.length > 0) {
        const device = gpu.amd.devices[0];
        gpuInfo = `${device.name}<br><small class="text-muted">${device.memory_total_gb.toFixed(1)} GB</small>`;
    }
    
    // 检查配置来源（per-model还是uniform）
    let configInfo = '';
    if (run.config_source === 'per_model') {
        configInfo = '<tr><td colspan="2" class="text-info"><small><i class="fas fa-layer-group"></i> 每个模型配置不同</small></td></tr>';
    } else if (run.warmup !== undefined && run.inputs !== undefined) {
        configInfo = `
            <tr>
                <td class="text-muted" style="width: 80px;">预热:</td>
                <td>${run.warmup} 次</td>
            </tr>
            <tr>
                <td class="text-muted">输入数:</td>
                <td>${run.inputs} 个</td>
            </tr>
        `;
    }
    
    return `
        <div style="min-width: 280px;">
            <h6 class="mb-2"><i class="fas fa-desktop"></i> 系统环境</h6>
            <table class="table table-sm table-borderless mb-0" style="font-size: 0.85rem;">
                <tr>
                    <td class="text-muted" style="width: 80px;">操作系统:</td>
                    <td>${system.os || 'N/A'} ${system.os_version || ''}</td>
                </tr>
                <tr>
                    <td class="text-muted">处理器:</td>
                    <td>${cpu.physical_cores || 'N/A'} 核 ${cpu.logical_cores || 'N/A'} 线程</td>
                </tr>
                <tr>
                    <td class="text-muted">GPU:</td>
                    <td>${gpuInfo}</td>
                </tr>
            </table>
            <hr class="my-2">
            <h6 class="mb-2"><i class="fas fa-cog"></i> 运行配置</h6>
            <table class="table table-sm table-borderless mb-0" style="font-size: 0.85rem;">
                ${configInfo}
                <tr>
                    <td class="text-muted" style="width: 80px;">时间戳:</td>
                    <td><small>${run.timestamp ? new Date(run.timestamp).toLocaleString('zh-CN') : 'N/A'}</small></td>
                </tr>
            </table>
            <div class="text-center mt-2">
                <small class="text-muted"><i class="fas fa-mouse-pointer"></i> 点击详情按钮查看完整信息</small>
            </div>
        </div>
    `;
}

/**
 * Get report data from cache or fetch from backend
 * 从缓存获取或从后端获取报告数据
 */
const reportCache = {};

function getReportData(reportId) {
    // 如果缓存中有，直接返回
    if (reportCache[reportId]) {
        return reportCache[reportId];
    }
    
    // 否则从后端获取（异步）
    $.ajax({
        url: `/api/reports/${reportId}`,
        method: 'GET',
        async: false,  // 同步请求以便立即返回
        success: function(data) {
            reportCache[reportId] = data;
        },
        error: function() {
            console.error(`Failed to fetch report: ${reportId}`);
        }
    });
    
    return reportCache[reportId] || null;
}

/**
 * Show device details in modal
 * 在Modal中显示设备详细信息
 */
function showDeviceDetails(reportId) {
    const report = getReportData(reportId);
    
    if (!report) {
        alert('无法加载设备信息');
        return;
    }
    
    // 填充Modal内容
    $('#deviceModalTitle').text(`设备详情: ${reportId}`);
    $('#deviceModalBody').html(generateDetailedContent(report, reportId));
    
    // 显示Modal
    const modal = new bootstrap.Modal(document.getElementById('deviceDetailsModal'));
    modal.show();
}

/**
 * Generate detailed content for modal
 * 生成Modal的详细内容
 */
function generateDetailedContent(report, reportId) {
    const env = report.env || {};
    const system = env.system || {};
    const cpu = env.cpu || {};
    const gpu = env.gpu || {};
    const adapter = env.adapter || {};
    const power = env.power || {};
    const run = report.run || {};
    const models = report.models || {};
    
    // GPU详细信息
    let gpuHtml = '<p class="text-muted">未检测到GPU</p>';
    if (gpu.nvidia && gpu.nvidia.devices && gpu.nvidia.devices.length > 0) {
        gpuHtml = '<div class="list-group">';
        gpu.nvidia.devices.forEach((device, idx) => {
            gpuHtml += `
                <div class="list-group-item">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1"><i class="fab fa-nvidia"></i> GPU ${idx}: ${device.name}</h6>
                        <small class="text-muted">Device ID: ${device.id}</small>
                    </div>
                    <p class="mb-1">
                        <strong>显存:</strong> ${device.memory_total_gb.toFixed(2)} GB<br>
                        <strong>驱动版本:</strong> ${device.driver_version}<br>
                        <strong>CUDA版本:</strong> ${device.cuda_version}
                    </p>
                </div>
            `;
        });
        gpuHtml += '</div>';
    } else if (gpu.amd && gpu.amd.devices && gpu.amd.devices.length > 0) {
        gpuHtml = '<div class="list-group">';
        gpu.amd.devices.forEach((device, idx) => {
            gpuHtml += `
                <div class="list-group-item">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1"><i class="fab fa-amd"></i> GPU ${idx}: ${device.name}</h6>
                        <small class="text-muted">Device ID: ${device.id}</small>
                    </div>
                    <p class="mb-1">
                        <strong>显存:</strong> ${device.memory_total_gb.toFixed(2)} GB
                    </p>
                </div>
            `;
        });
        gpuHtml += '</div>';
    }
    
    // 模型信息
    const modelCount = Object.keys(models).length;
    const modelNames = Object.keys(models).join(', ');
    
    return `
        <div class="accordion" id="deviceDetailsAccordion">
            <!-- 系统信息 -->
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingSystem">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSystem">
                        <i class="fas fa-desktop me-2"></i> 系统信息
                    </button>
                </h2>
                <div id="collapseSystem" class="accordion-collapse collapse show" data-bs-parent="#deviceDetailsAccordion">
                    <div class="accordion-body">
                        <table class="table table-sm">
                            <tr><th style="width: 150px;">操作系统</th><td>${system.os || 'N/A'}</td></tr>
                            <tr><th>系统版本</th><td>${system.os_version || 'N/A'}</td></tr>
                            <tr><th>平台</th><td>${system.platform || 'N/A'}</td></tr>
                            <tr><th>架构</th><td>${system.architecture || 'N/A'}</td></tr>
                            <tr><th>处理器</th><td>${system.processor || 'N/A'}</td></tr>
                            <tr><th>Python版本</th><td>${system.python_version || 'N/A'} (${system.python_implementation || 'N/A'})</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- CPU信息 -->
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingCPU">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseCPU">
                        <i class="fas fa-microchip me-2"></i> CPU信息
                    </button>
                </h2>
                <div id="collapseCPU" class="accordion-collapse collapse" data-bs-parent="#deviceDetailsAccordion">
                    <div class="accordion-body">
                        <table class="table table-sm">
                            <tr><th style="width: 150px;">物理核心</th><td>${cpu.physical_cores || 'N/A'}</td></tr>
                            <tr><th>逻辑核心</th><td>${cpu.logical_cores || 'N/A'}</td></tr>
                            <tr><th>当前频率</th><td>${cpu.freq_current_mhz ? cpu.freq_current_mhz.toFixed(0) + ' MHz' : 'N/A'}</td></tr>
                            <tr><th>最大频率</th><td>${cpu.freq_max_mhz ? cpu.freq_max_mhz.toFixed(0) + ' MHz' : 'N/A'}</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- GPU信息 -->
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingGPU">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseGPU">
                        <i class="fas fa-video me-2"></i> GPU信息
                    </button>
                </h2>
                <div id="collapseGPU" class="accordion-collapse collapse" data-bs-parent="#deviceDetailsAccordion">
                    <div class="accordion-body">
                        ${gpuHtml}
                    </div>
                </div>
            </div>
            
            <!-- 运行配置 -->
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingRun">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseRun">
                        <i class="fas fa-cog me-2"></i> 运行配置
                    </button>
                </h2>
                <div id="collapseRun" class="accordion-collapse collapse" data-bs-parent="#deviceDetailsAccordion">
                    <div class="accordion-body">
                        <table class="table table-sm">
                            <tr><th style="width: 150px;">预热次数</th><td>${run.warmup || 'N/A'}</td></tr>
                            <tr><th>输入数量</th><td>${run.inputs || 'N/A'}</td></tr>
                            <tr><th>设备ID</th><td>${run.device_id !== undefined ? run.device_id : 'N/A'}</td></tr>
                            <tr><th>采样率</th><td>${run.sample_rate_hz ? run.sample_rate_hz + ' Hz' : 'N/A'}</td></tr>
                            <tr><th>适配器后端</th><td>${run.adapter_backend || adapter.backend || 'N/A'}</td></tr>
                            <tr><th>功耗后端</th><td>${run.power_backend || power.backend || 'N/A'}</td></tr>
                            <tr><th>功耗采样</th><td>${run.power_sampling ? '是' : '否'}</td></tr>
                            <tr><th>运行时间</th><td>${run.timestamp ? new Date(run.timestamp).toLocaleString('zh-CN') : 'N/A'}</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- 测试模型 -->
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingModels">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseModels">
                        <i class="fas fa-layer-group me-2"></i> 测试模型 (${modelCount})
                    </button>
                </h2>
                <div id="collapseModels" class="accordion-collapse collapse" data-bs-parent="#deviceDetailsAccordion">
                    <div class="accordion-body">
                        <div class="alert alert-info mb-2">
                            <strong>包含模型:</strong> ${modelNames || '无'}
                        </div>
                        ${generateModelConfigTable(models)}
                    </div>
                </div>
            </div>
        </div>
    `;
}

/**
 * Generate model configuration table
 * 生成模型配置表格（显示每个模型的inputs/warmup）
 */
function generateModelConfigTable(models) {
    if (!models || Object.keys(models).length === 0) {
        return '';
    }
    
    // 检查是否有per-model配置
    let hasPerModelConfig = false;
    for (const modelData of Object.values(models)) {
        if (modelData.config) {
            hasPerModelConfig = true;
            break;
        }
    }
    
    if (!hasPerModelConfig) {
        return '';
    }
    
    let tableHtml = `
        <h6 class="mt-3 mb-2">Per-Model 配置</h6>
        <table class="table table-sm table-bordered">
            <thead class="table-light">
                <tr>
                    <th>模型</th>
                    <th>输入数</th>
                    <th>预热数</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    for (const [modelName, modelData] of Object.entries(models)) {
        if (modelData.config) {
            tableHtml += `
                <tr>
                    <td><strong>${modelName}</strong></td>
                    <td>${modelData.config.inputs || 'N/A'}</td>
                    <td>${modelData.config.warmup || 'N/A'}</td>
                </tr>
            `;
        }
    }
    
    tableHtml += `
            </tbody>
        </table>
    `;
    
    return tableHtml;
}

/**
 * Update details comparison table
 */
function updateDetailsTable(data) {
    const header = $('#detailsTableHeader');
    const tbody = $('#detailsTableBody');
    
    header.empty();
    tbody.empty();
    
    // Build header
    header.append('<th>指标</th>');
    data.scores.forEach(score => {
        header.append(`<th>${score.id}</th>`);
    });
    
    // Metrics to display
    const metrics = [
        { key: 'qps', label: 'QPS (查询/秒)', format: v => v.toFixed(2) },
        { key: 'lat_avg_ms', label: '平均延迟 (ms)', format: v => v.toFixed(2) },
        { key: 'p50_ms', label: 'P50 延迟 (ms)', format: v => v.toFixed(2) },
        { key: 'p99_ms', label: 'P99 延迟 (ms)', format: v => v.toFixed(2) },
        { key: 'perf_per_W', label: '能效 (QPS/W)', format: v => v ? v.toFixed(2) : 'N/A' },
        { key: 'rss_mb', label: '内存占用 (MB)', format: v => v.toFixed(1) },
        { key: 'vram_mb', label: '显存占用 (MB)', format: v => v ? v.toFixed(1) : 'N/A' }
    ];
    
    metrics.forEach(metric => {
        const row = $('<tr>');
        row.append($('<td>').html(`<strong>${metric.label}</strong>`));
        
        const values = [];
        data.scores.forEach(score => {
            const stats = score.stats || {};
            const value = stats[metric.key];
            values.push({ score: score, value: value });
        });
        
        // Find best/worst for highlighting
        const numericValues = values.map(v => typeof v.value === 'number' ? v.value : null).filter(v => v !== null);
        const best = metric.key === 'lat_avg_ms' || metric.key === 'p50_ms' || metric.key === 'p99_ms' || metric.key === 'rss_mb' || metric.key === 'vram_mb' 
            ? Math.min(...numericValues) 
            : Math.max(...numericValues);
        
        values.forEach(item => {
            const td = $('<td>');
            const displayValue = typeof item.value === 'number' ? metric.format(item.value) : 'N/A';
            
            if (item.value === best && typeof item.value === 'number') {
                td.addClass('metric-best');
            }
            
            td.text(displayValue);
            row.append(td);
        });
        
        tbody.append(row);
    });
}

/**
 * Upload report dialog
 */
function uploadReport() {
    $('#uploadModal').modal('show');
}

/**
 * Submit uploaded file
 */
function submitUpload() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    
    if (!file) {
        $('#uploadStatus').html('<div class="alert alert-danger">请选择文件</div>');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    $.ajax({
        url: '/api/upload',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {
            $('#uploadStatus').html('<div class="alert alert-success">上传成功！</div>');
            setTimeout(() => {
                $('#uploadModal').modal('hide');
                loadReports();
            }, 1500);
        },
        error: function(xhr, status, error) {
            const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : error;
            $('#uploadStatus').html(`<div class="alert alert-danger">上传失败：${errorMsg}</div>`);
        }
    });
}

/**
 * Export comparison data
 */
function exportData() {
    if (!currentScores) {
        alert('请先计算评分');
        return;
    }
    
    const requestData = {
        report_ids: reports.map(r => r.id),
        format: 'csv'
    };
    
    // Create a form and submit to download
    const form = $('<form>', {
        method: 'POST',
        action: '/api/export'
    });
    
    const input = $('<input>', {
        type: 'hidden',
        name: 'data',
        value: JSON.stringify(requestData)
    });
    
    form.append(input);
    $('body').append(form);
    form.submit();
    form.remove();
    
    // Alternative: using fetch and blob
    fetch('/api/export', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
    })
    .then(response => response.blob())
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'benchmark_comparison.csv';
        document.body.appendChild(a);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
    })
    .catch(error => {
        console.error('Export failed:', error);
        alert('导出失败：' + error);
    });
}

